20180724 一步步教你在Python使用Google Maps API

所謂API是指Application Programming Interface的縮寫,
通常是提供給第三方開發者使用其資料,藉此來開發各種應用來強化他們的產品,
比如說Google Map的API就提供地圖服務的資訊,第三方則能使用服務來開發其他應用。
當然裏頭也有些商業模式,比如說流量限制來收費之類的。

萬事起頭難,此節為Python調用Google Maps資料的行前準備,
接下來我們就來一步步教學,如何建立Googel Maps的API專案並使用在Python上。

  • 一、建立專案並加入API
    我們需要建立一個Google的API專案,並把需要用到的API加入專案之中。

  • 二、取得憑證 (API KEY)

    往後調用API裏頭的資料,直接就從憑證進入(跳過每次需要帳號密碼的不安全過程), 所以還需要建立一個API的憑證。

  • 三、安裝Python Client for Google Maps Services
    在你的python上裝上google map的模組。

  • 四、Python調用Google Maps API的方法
    簡單示範在python上使用API的方法,往後會有更多應用。

Step by Step

一、建立專案並加入API

1.要有個Google帳號

2.進到 Google API程式庫頁面

3.搜尋關鍵字 "Maps"

4.找到要使用的API (如有Places API, Geocoding API),進入之後再按啟用

5.Google會要求你建立API專案,按建立進入後,隨便取個名字新增專案。

6.重複步驟加入需要的API到專案裏頭,並確認API有正確加入專案

二、取得API的key

1.進入Google Maps Plateform 開發者頁面來取得API Key

2.選擇剛剛的建立的專案,按下NEXT來取得API KEY,複製並保存下來。

3.如果忘記API KEY,可回專案內重新確認

三、安裝Python Client for Google Maps Services

1.安裝方法: cmd執行 pip3 install-U googlemaps

開源頁面:https://github.com/googlemaps/google-maps-services-python

四、Python調用Google Maps API的方法

#導入模組
import googlemaps

#將API憑證用以下指令包起來
gmaps=googlemaps.Client(key="這裡輸入你的API KEY")

#簡單的調用資料示範
geocode_result = gmaps.geocode("臺北市")
geocode_result
####Output####
[{'address_components': [{'long_name': 'Taipei',
    'short_name': 'Taipei',
    'types': ['colloquial_area', 'locality', 'political']},
   {'long_name': 'Taiwan',
    'short_name': 'TW',
    'types': ['country', 'political']}],
  'formatted_address': 'Taipei, Taiwan',
  'geometry': {'bounds': {'northeast': {'lat': 25.2443731, 'lng': 121.7300824},
    'southwest': {'lat': 24.7900797, 'lng': 121.2826735}},
   'location': {'lat': 25.0329694, 'lng': 121.5654177},
   'location_type': 'APPROXIMATE',
   'viewport': {'northeast': {'lat': 25.2443731, 'lng': 121.7300824},
    'southwest': {'lat': 24.7900797, 'lng': 121.2826735}}},
  'place_id': 'ChIJmQrivHKsQjQR4MIK3c41aj8',
  'types': ['colloquial_area', 'locality', 'political']}]

results matching ""

    No results matching ""